package org.ccccye.distributedlocks.redis;

import org.ccccye.distributedlocks.DistributedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedissonLock implements DistributedLock {
    @Resource
    private RedissonClient redissonClient;

    @Override
    public boolean tryLock(String key, String value) {
        return getLock(key).tryLock();
    }

    @Override
    public boolean tryLock(String key, String value, int timeout) {
        RLock rLock = getLock(key);
        try {
            return rLock.tryLock(timeout, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void unLock(String key, String value) {
        RLock rLock = getLock(key);
        if (rLock.isLocked()) {
            rLock.unlock();
        }
    }

    private RLock getLock(String key) {
        return redissonClient.getLock(key);
    }
}
